package com.shushan.mixedexam;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.android.permission.FloatPermissionUtil;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.mixedexam.bean.OcRecordDetailBean;
import com.shushan.mixedexam.oralcalculation.bean.OCExerciseResultBean;
import com.shushan.mixedexam.oralcalculation.bean.OralCalculateExamBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.permission.OpenWindowActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.ControlUtil;
import com.shushan.util.DateUtils;
import com.shushan.util.DensityUtil;
import com.shushan.util.DialogUtil;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.GoodsDetailWebActivity;

/**
 * @ClassName: OralCalculateScoreActivity
 * @Desciption: //口算练习得分界面
 * @author: zhangshihao
 * @date: 2018-08-14
 */
public class OralCalculateScoreActivity extends BaseActivity implements View.OnClickListener,Animation.AnimationListener {

    private static final String TAG = OralCalculateScoreActivity.class.getSimpleName();

    private TextView tvExercisePerformance;
    private Button btnWrongTopicCount;
    private Button btnRightTopicCount;
    private Button btnWatchTopic;
    private Button btnContinueExercise;
    private TextView tvUseTime;
    private ImageView ivUseNow;
    private TextView tvGetTimeCondition;
    private TextView tvRewardStarCount;
    private ImageView ivExchangeReward;
    private ImageView ivSurpriseImg;
    private RelativeLayout rlFirstToy;

    private OralCalculateExamBean oralExamBean;
    private OCExerciseResultBean ocResultBean;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    private int coseTime = 0;
    private int completeTopicCount = 0;
    private int paperId = 0;
    private boolean fromRecord = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenManager.getInstance().setStatusBar(true, this);
        setContentView(R.layout.activity_oral_calculate_score);

        oralExamBean = (OralCalculateExamBean) Session.getSession().get("oralExamBean");
        ocResultBean = (OCExerciseResultBean) Session.getSession().get("ocResultBean");
        coseTime = getIntent().getIntExtra("coseTime",0);
        completeTopicCount = getIntent().getIntExtra("completeTopicCount",0);
        paperId = getIntent().getIntExtra("paper_id",0);
        fromRecord = getIntent().getBooleanExtra("fromRecord",false);

        initView();
        if(oralExamBean == null && ocResultBean == null){
            getData();
        }else {
            initData();
        }
    }

    private void initView() {
        tvExercisePerformance = findViewById(R.id.tv_exercise_performance);
        btnWrongTopicCount = findViewById(R.id.btn_wrong_topic_count);
        btnRightTopicCount = findViewById(R.id.btn_right_topic_count);
        btnWatchTopic = findViewById(R.id.btn_watch_topic);
        btnWatchTopic.setOnClickListener(this);
        btnContinueExercise = findViewById(R.id.btn_continue_exercise);
        btnContinueExercise.setOnClickListener(this);
        if(fromRecord){
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(this,250f), LinearLayout.LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            btnWatchTopic.setLayoutParams(params);
            btnContinueExercise.setVisibility(View.GONE);
        }
        tvUseTime = findViewById(R.id.tv_get_time);
        ivUseNow = findViewById(R.id.iv_use_now);
        ivUseNow.setOnClickListener(this);
        tvGetTimeCondition = findViewById(R.id.tv_get_time_condition);
        tvRewardStarCount = findViewById(R.id.tv_reward_star_num);
        ivExchangeReward = findViewById(R.id.iv_exchange_reward);
        ivExchangeReward.setOnClickListener(this);
        ivSurpriseImg = findViewById(R.id.iv_surprise_img);
        rlFirstToy = findViewById(R.id.rl_first_toy);
    }



    private void initData() {
        if(ocResultBean == null){
            return;
        }
        btnWrongTopicCount.setText("做错："+ocResultBean.error_count);
        btnRightTopicCount.setText("做对："+ocResultBean.right_count);
        tvUseTime.setText(ocResultBean.reward_time+"");
        tvExercisePerformance.setText(getCompleteStateStr());
        if(ocResultBean.reward_time == 0 || fromRecord){
            ivUseNow.setVisibility(View.GONE);
            if(ocResultBean.reward_time == 0) {
                tvGetTimeCondition.setVisibility(View.VISIBLE);
                tvGetTimeCondition.setText(ocResultBean.reward_description);
            }
        }else if(ocResultBean.reward_time > 0){
            ControlUtil.addGameTime(ocResultBean.reward_time);
        }

        tvRewardStarCount.setText(ocResultBean.stars_num+"");
        if(!fromRecord) {
            if (TextUtils.isEmpty(ocResultBean.first_toy)) {
                startSurpriseAnimation(this);
                rlFirstToy.setVisibility(View.VISIBLE);
            }
        }

        //将该次练习得到的学贝数记入本地
        if(!fromRecord) {
            shuShanApplication.updateStars(ocResultBean.stars_num);
        }
    }

//    private String getRewardDescription(){
//        StringBuffer sb = new StringBuffer();
//        sb.append("练习产生")
//                .append(ocResultBean.error_count)
//                .append("道错题，需要继续练习且做对")
//                .append(ocResultBean.num)
//                .append("道题，才能获得手机使用时间。");
//        return sb.toString();
//    }

    private void getData(){
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL).appendRegion(UrlConst.EXERCISE_DETAILS_NEW);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id",childId)
                .putValue("paper_id",paperId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<OcRecordDetailBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(OcRecordDetailBean ocRecordDetailBean) {
                        if(ocRecordDetailBean == null){
                            return;
                        }
                        oralExamBean = ocRecordDetailBean.examBean;
                        ocResultBean = ocRecordDetailBean.resultBean;
                        coseTime = ocResultBean.total * 60;
                        completeTopicCount = ocResultBean.right_count+ocResultBean.error_count;

                        initData();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private String getCompleteStateStr(){
        StringBuffer sb = new StringBuffer();
        int i = 1;
        while(true){
            if(coseTime <= (i*60)) {
                break;
            }
            i++;
        }
        sb.append(i)
          .append("分钟")
          .append("完成")
          .append(completeTopicCount)
          .append("道题");
        return sb.toString();
    }

    private void startSurpriseAnimation(Animation.AnimationListener listener) {
        ivSurpriseImg.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.scale_normal_to_harf);
        ivSurpriseImg.setAnimation(animation);
        ivSurpriseImg.startAnimation(animation);
        animation.setAnimationListener(listener);
    }

    @Override
    public void onAnimationStart(Animation animation) {
        //do nothing
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        ivSurpriseImg.setVisibility(View.GONE);
        DialogUtil.showSurpriseDialog(this, this);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        //do nothing
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_watch_topic://查看错题
                if(oralExamBean != null) {
                    if(ocResultBean != null && ocResultBean.error_count <= 0){
                        showToast("无错题");
                        return;
                    }

                    Session.getSession().put("oralExamBean", oralExamBean);

                    Intent intent = new Intent(this, OralCalculateExamActivity.class);
                    intent.putExtra(Constants.SCORE_RESULT_JUMP_TYPE, Constants.JUMP_TYPE_WRONG_TOPIC_WATCH);
                    intent.putExtra("fromRecord",fromRecord);
                    startActivityAllow(intent);
                }else{
                    showToast("题目数据为空");
                }
                break;
            case R.id.btn_continue_exercise://继续练习
                onBackAction();
                break;
            case R.id.iv_use_now://立即使用
                gotoGamesFloat();
                break;
            case R.id.iv_exchange_reward://兑换奖品
                startActivity(MyStarActivity.class);
                break;
            case R.id.btn_get_reward://第一次练习奖励：立即领取奖品
            case R.id.iv_get_system_toy_now://立即领取
                //跳转奖品展示网页
                gotoToyWeb();
                DialogUtil.dismissDialog();
                break;
        }
    }

    private void gotoToyWeb() {
        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        UserBean currentUserBean = shuShanApplication.getUserBean();
        int childId = currentChildBean.id;
        UrlParse urlParse = new UrlParse(/*UrlConst.BASE_URL*/"https://tpi.shushan.com")
                .appendRegion(UrlConst.DIST_TOY_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "")
                .putValue("starsnum",currentChildBean.stars)
                .putValue("goodsid",0)
                .putValue("viptype",ToolUtils.getVipTypeForGoodsDetails(currentUserBean))
                ;
        Intent intent = new Intent(this, GoodsDetailWebActivity.class);
        intent.putExtra("title", "奖品详情");
        intent.putExtra("url", urlParse.toString());
        startActivityForResultAllow(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 200){
            showToast("领取成功");
            rlFirstToy.setVisibility(View.GONE);
        }else if(resultCode == 500){//玩具详情点击购买
            startActivity(OpenVipSpendActivity.class);
        }
    }

    private void gotoGamesFloat() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl){
            showToast("请先进入家长模式开启管控");
            return;
        }

        boolean isAllowPlay = SharedPreferencesUtils.getBooleanDates(Constants.ALLOW_PLAY_SWITCH_SHAREPREFERS_KEY);
        if(!isAllowPlay){
            showToast("允许学习换取娱乐时间的开关已关闭");
            return;
        }

        if(SystemUtils.checkUsagePermission(this) && FloatPermissionUtil.checkPermission(this)){
            if(ocResultBean != null){
                setAllowBack(true);
                ActivityStackManager.getActivityStackManager().popAllActivity();

                GamesFloatWindow gamesFloatWindow = new GamesFloatWindow(shuShanApplication);
                gamesFloatWindow.setPaperId(ocResultBean.paper_id);
                GamesWindowManager.setGamesFloatWindow(gamesFloatWindow);
                GamesWindowManager.createGamesFloatWindow(shuShanApplication);

                //开启玩耍手机时间的闹钟
                setChildFree(ocResultBean.reward_time);
            }else {
                showToast("考试结果数据为空");
                return;
            }
        }else if(! FloatPermissionUtil.checkPermission(this)){
            showNoFloatDialog();
        } else if(!SystemUtils.checkUsagePermission(this)){
            showNoUsageDialog();
        }
    }

    private void setChildFree(int freeTime) {
        Log.i(TAG, "freeTime=" + freeTime + " setChildFree:" + DateUtils.getNowDate());

        if (freeTime > 0) {
            ToolUtils.setLockAlarm(this, freeTime);
        }
    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    private void showNoFloatDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您的手机没有授予悬浮窗权限，请开启后再试")
                .setNegativeButton("暂不开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("现在去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenWindowActivity.class);
                    }
                })
                .create().show();
    }

}
